package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.SecurityContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVo orderTradeData() {
        List<OrderItem> orderItemList = null;
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        //1.远程调用购物车接口，获取所有勾选的商品 List<CartInfo>
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (cartCheckedList.getCode() == R.FAIL) {
            throw new ServiceException(cartCheckedList.getMsg());
        }
        List<CartInfo> cartCheckeddataList = cartCheckedList.getData();
        if (CollectionUtils.isEmpty(cartCheckeddataList)) {
            throw new ServiceException("购物车中没有选中的sku");
        }
        //2.类型转换  List<CartInfo> -> List<OrderItem> //将集合泛型从购物车改为订单明细
        orderItemList = cartCheckeddataList.stream().map(cartCheckeddata -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartCheckeddata, orderItem);
            return orderItem;
        }).toList();

        //3.计算商品总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        //4.生成订单流水号。下单是用于去重。也是订单表的订单号。
        String tradeNo = getTradeNo(userId);
        //渲染订单确认页面-生成用户流水号
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setTradeNo(tradeNo);

        return tradeVo;
    }

    //专业生产订单流水号
    private String getTradeNo(Long userId) {
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //1.构建流水号Key
        String key = "user:tradeNo:" + userId;
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(key, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        //todo 1 判断用户提交的 表单是否重复提交、
        //从用户提交的表单中 拿取表单中的订单号
        String tradeNo = orderForm.getTradeNo();
        //从redis中拿取保存的订单号 对比判断是否一致即判断是否为重复提交 超过时间删除 提交后删除
        Long userId = SecurityContextHolder.getUserId();
        String tradeNoKey = "user:tradeNo:" + userId;
        //使用lua脚本保证原子操作
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then\n" +
                "\treturn redis.call('del',KEYS[1])\n" +
                "else\n" +
                "\treturn 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);
        Long result = (Long) redisTemplate.execute(redisScript, Arrays.asList(tradeNoKey), tradeNo);

        if (result != 1) {
            throw new ServiceException("重复提交");
        }
        //todo 2 判断表单信息 是否为空
        //从提交的表单中获取 结算商品列表 list信息
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("购物车信息为空");
        }
        //todo 3 校验价格
        //从提交的表单中  结算商品列表中获取skuid的list
        List<Long> itemSkuidList = orderItemList.stream().map(orderItem -> orderItem.getSkuId()).toList();
        //通过远程接口 获取批量skuid list 的价格
        R<List<SkuPrice>> skuPriceResult = remoteProductService.getSkuPriceList(itemSkuidList, SecurityConstants.INNER);
        if (skuPriceResult.getCode() == R.FAIL) {
            throw new ServiceException(skuPriceResult.getMsg());
        }
        //从批量skuid价格list 中获取data
        List<SkuPrice> SkuPriceData = skuPriceResult.getData();
        //将SkuPriceData转换为 skuid与对应价格 的map
        Map<Long, BigDecimal> SkuPriceToMap = SkuPriceData.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        //循环表单 比较价格是否与数据库一致
        StringBuilder stringBuilder = new StringBuilder("");
        for (OrderItem orderItem : orderItemList) {
            //从SkuPriceToMap 数据库信息中 找出对应skuid 的价格
            BigDecimal bigDecimal = SkuPriceToMap.get(orderItem.getSkuId());
            //对比表单价格与数据库价格
            if (orderItem.getSkuPrice().compareTo(bigDecimal) != 0) {
                stringBuilder.append("商品【" + orderItem.getSkuName() + "】的价格有变动");
            }
            //通过判断stringBuilder 字符串长度 判断是否有变动 有变动 则通过远程结构调用更新购物车价格方法
            if (stringBuilder.toString().length() > 0) {
                //更新购物车价格
                remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
                throw new SecurityException(stringBuilder.toString());
            }
        }

        //todo 4 锁定库存
        List<SkuLockVo> skuLockVos = orderItemList.stream().map(item -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(item.getSkuId());
            skuLockVo.setSkuNum(item.getSkuNum());
            return skuLockVo;
        }).toList();
        String data = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVos, SecurityConstants.INNER).getData();
        if (StringUtils.isNotEmpty(data)) {
            throw new ServiceException(data);
        }

        //todo 5 保存订单信息
        //定义保存订单后的 订单id
        Long orderId = null;
        //通过 调用事务方法 保存订单数据 确保一致性
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            // 出现异常 解锁库存 - 发消息异步解锁
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            throw new RuntimeException(e);
        }
        //todo 6 删除下单的购物车信息
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);
        //todo 7 延迟消息 超过规定时间未支付 关闭订单  (15分钟未支付，消费者就会进行关闭订单->解锁库存。)
        rabbitService.sendDealyMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId), MqConst.CANCEL_ORDER_DELAY_TIME);
        return orderId;
    }

    @Transactional
    protected Long saveOrder(OrderForm orderForm) {
        //获取当前登录用户的 id name
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        //todo 1.保存订单数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo()); //订单号
        orderInfo.setUserId(userId);  //会员_id
        orderInfo.setNickName(userName); //昵称
        //orderInfo.setRemark(orderForm.getRemark());//备注

        BeanUtils.copyProperties(orderForm, orderInfo);
        //远程调用用户 地址接口 根据地址id 获取地址
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();

        orderInfo.setReceiverName(userAddress.getName());//收货人姓名
        orderInfo.setReceiverPhone(userAddress.getPhone());//收货人电话
        orderInfo.setReceiverTagName(userAddress.getTagName());//收货人地址标签
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());//省份/直辖市
        orderInfo.setReceiverCity(userAddress.getCityCode());//城市
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());//区
        orderInfo.setReceiverAddress(userAddress.getFullAddress());//详细地址

        //获取订单数据中的订单列表
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal bigDecimal = new BigDecimal(0);
        //循环遍历 表单列表 累加 商品价格
        for (OrderItem orderItem : orderItemList) {
            bigDecimal = bigDecimal.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(bigDecimal);//实付总价格（含优惠券和运费）
        orderInfo.setCouponAmount(new BigDecimal(0));//优惠券
        orderInfo.setOriginalTotalAmount(bigDecimal);//商品总价格
        //orderInfo.setFeightFee(orderForm.getFeightFee());//运费
        orderInfo.setOrderStatus(0);//订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】


        //保存数据库 主键回填
        orderInfoMapper.insert(orderInfo);
        //todo 2.保存订单项数据
        //遍历订单数据中的订单列表 依次保存数据库  private List<OrderItem> orderItemList;
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }
        //todo 3.保存订单日志数据
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());//订单id
        orderLog.setProcessStatus(0); //订单状态 【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        orderLog.setNote("提交订单"); //备注
        orderLog.setOperateUser("用户");//操作人：用户；系统；后台管理员
        //保存数据库
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void prossCloseOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        //  订单状态orderStatus=0 说明15分钟未支付。
        if (null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);
        }
        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(-1); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        orderLog.setNote("系统取消订单");
        orderLogMapper.insert(orderLog);
        //发送MQ消息通知商品系统解锁库存
        rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void processPaySuccess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo).select(OrderInfo::getId, OrderInfo::getOrderStatus));
        //未支付
        if (orderInfo.getOrderStatus().intValue()==0) {
            orderInfo.setOrderStatus(1); //已支付
            orderInfo.setPaymentTime(new Date()); //支付时间
            orderInfoMapper.updateById(orderInfo);
        }
    }
}